在以往的網頁開發中,實際檔案的儲存一直是很麻煩的課題,有可能會受到硬碟空間大小的限制,或是不同台機器要共用Filer,還有如何確保檔案不會遺失等等,有許許多多的眉眉角角,也是無形的一種管理成本開銷,而Azure提供了專門的Storage服務,甚至還提供地理備援機制,讓我們檔案服務的可靠度大大提升,今天就要來像大家介紹如何在API中實現簡單的圖片上傳機制。
※開啟Azure Storage服務
首先我們先來建立一個儲存體用來存放圖片
 
 
 
※新增商品圖片修改功能
在提供上傳圖片的服務之前,我們先在商品新增一個欄位來儲存圖片網址,並且提供一個方法讓使用者可以修改它的商品圖片。
修改Product Class,新增圖片欄位
    public class Product : EntityBase
    {            
        [StringLength(300)]
        public string ImagePath { get; set; }            
    }    
在套建管理員新增Migration和更新資料庫
    Add-Migration AddProductImagePath
    Update-Database
在DA建立修改商品圖片的程式碼
    public interface IProductRepository
    {
        IEnumerable<ProductForCategoryModel> GetProductByCategoryId(int categoryId);
        void InsertProduct(ProductModel productModel);
        void UpdateProductImagePath(int id, string imagePath);
    }
    public class ProductRepository : IProductRepository
    {
        public ShopContext ShopContext { get; set; }
        public ProductRepository(ShopContext context)
        {
            this.ShopContext = context;
        }
        public void UpdateProductImagePath(int id, string imagePath)
        {
            var product = this.ShopContext.Products
                                          .Where(i => i.Id == id)
                                          .FirstOrDefault();
            if (product != null)
            {
                product.ImagePath = imagePath;
            }
            this.ShopContext.SaveChanges();
        }
    }        
※新增Azure檔案上傳服務
網址格式: http://hostname/{Container}/{Id}/{FileName}
        public interface IFileRepository
        {
            string UploadFile(string containerName, string groupName, HttpPostedFileBase file);
        }
使用Nuget加入Azure.Storage Library

到Azure儲存體點選管理儲存金鑰

記下主要金鑰內容

在網站的AppSetting新增Storage的連線字串,包含主要金鑰
    <add key="azure.blob.connectionstring" value="DefaultEndpointsProtocol=https;AccountName=apiimage;AccountKey=xxxx;BlobEndpoint=http://apiimage.blob.core.windows.net/" />
撰寫上傳檔案至Azure Storage的程式碼
    public class FileRepository : IFileRepository
    {
        public string UploadFile(string containerName, string groupName, HttpPostedFileBase file)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("azure.blob.connectionstring"));
            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            // Retrieve a reference to a container. 
            CloudBlobContainer container = blobClient.GetContainerReference(containerName.ToLower());
            // Create the container if it doesn't already exist.
            container.CreateIfNotExists();
            container.SetPermissions(
                     new BlobContainerPermissions
                     {
                         PublicAccess =
                             BlobContainerPublicAccessType.Blob
                     });
            var fileName = groupName + "/" + file.FileName;
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
            blockBlob.Properties.ContentType = file.ContentType;
            blockBlob.UploadFromStream(file.InputStream);
            return blockBlob.Uri.AbsoluteUri;
        }
    }
延伸閱讀:
* How to use the Windows Azure Blob Storage Service in .NET
※測試圖片上傳
接下來我們模擬上傳圖片,測試是否有上傳到Azure Storage和更新商品圖片
 
 
 
 
※本日小結
透過Azure Storage服務,可以非常快速的就實現檔案上傳,也可以讓我們省去許多管理儲存空間的麻煩,例如像File Server的維護,還能提供高可用性的儲存空間,甚至是異地備援等等,而在使用上也擁有非常多的彈性,更不需要擔心硬碟空間不足的問題,大家可以依照自己的需求評估使用,關於今天的內容歡迎大家一起討論 ^_^